package com.ikingtech.platform.service.system.dept.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ikingtech.framework.sdk.organization.api.OrgDeptApi;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.system.dept.entity.DepartmentDO;
import com.ikingtech.platform.service.system.dept.service.repository.DeptRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author tie yan
 */
@Service
@RequiredArgsConstructor
public class OrgDeptService implements OrgDeptApi {

    private final DeptRepository service;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void moveDepartment(String parentOrgId, List<String> orgIds) {
        List<DepartmentDO> entities = this.service.list(Wrappers.<DepartmentDO>lambdaQuery().in(DepartmentDO::getOrgId, orgIds));
        this.service.updateBatchById(Tools.Coll.traverse(entities, entity -> {
            entity.setOrgId(parentOrgId);
            return entity;
        }));
    }

    @Override
    public List<String> loadDepartmentIds(String orgId) {
        return this.service.listObjs(Wrappers.<DepartmentDO>lambdaQuery()
                .select(DepartmentDO::getId)
                .eq(DepartmentDO::getOrgId, orgId), String.class::cast);
    }

    @Override
    public List<String> loadOrganizationIdByDepartmentIds(List<String> deptIds) {
        return this.service.listObjs(Wrappers.<DepartmentDO>lambdaQuery()
                .select(DepartmentDO::getOrgId)
                .in(DepartmentDO::getId, deptIds), String.class::cast);
    }
}
